<?php
/**
 * Created by PhpStorm.
 * User: sky
 * Date: 2019/7/16
 * Time: 23:04
 */

namespace App\Repositories;


use App\Models\Roles;

class RolesRepositories
{
    public function model()
    {
        return Roles::query();
    }

    public function find($id)
    {
        return $this->model()->with(['manyPermissions'])->where('id',$id)->first();
    }

    public function save($data)
    {
        $roles = $this->model()->create($data);
        if(isset($data['permissions']) && !empty($data['permissions']) )
        {
            //$categoryId =explode(',',$data['category_id']);
            $roles->manyPermissions()->sync($data['permissions']);
        }
        return $roles;
    }
    public function update($id,$data)
    {
        $updateData=[
            'name'=>$data['name'],
            'slug'=>$data['slug'],
        ];
        $roles =$this->find($id);
        if($roles->update($updateData))
        {
            if(isset($data['permissions']) && !empty($data['permissions']) )
            {
                $roles->manyPermissions()->sync($data['permissions']);
            }
            return true;
        }

        return false;
    }

    public function search($data)
    {
        $model = $this->model();

        if(isset($data['name']))
        {
            $model = $model->where('name','like','%'.$data['name'].'%');
        }

        //些处扩展更多查询条件
        return $model->orderBy('created_at','desc')->paginate($data['limit'])->toArray();
    }

    public function delete($ids)
    {
        return Roles::destroy($ids);
    }

    public function all()
    {
        return $this->model()->get()->toArray();
    }



}